package com.udata.server.dao.impl;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.udata.server.PMF;
import com.udata.server.dao.UserDao;
import com.udata.server.model.User;
import com.udata.shared.exception.OperationException;
import com.udata.shared.model.UserB;

public class UserDaoImpl extends UserDao {
	@Override
	public UserB save(UserB userB) throws OperationException {
		User user = new User(userB);

		try {
			userB = this.load(userB.getId());
			if (userB == null) {
				PersistenceManager pm = PMF.get().getPersistenceManager();
				pm.makePersistent(user);
				pm.close();
			} else {
				throw new OperationException(this.getClass().getCanonicalName()
						+ ".save\n" + "User already exist");
			}
		} catch (Exception e) {
			throw new OperationException(this.getClass().getCanonicalName()
					+ ".save\n" + e.getMessage());
		}
		return user.getBean();

	}

	@Override
	public UserB load(String id) throws OperationException {
		User result = null;
		try {
			PersistenceManager pm = PMF.get().getPersistenceManager();
			result = pm.getObjectById(User.class, id);
			pm.close();
			return result.getBean();
		} catch (Exception e) {
			System.out.println("Can not load user id=" + id);
			return null;
		}

	}

	@Override
	public UserB getUser(String id, String password) throws OperationException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(User.class);
		query.setFilter("id == '" + id + "'&&password=='" + password+"'");
		List<User> userList = (List<User>) query.execute();
		if (userList.size() == 0) {
			throw new OperationException(this.getClass().getCanonicalName()
					+ ".getUser\n User " + id
					+ " doesn't exist or password is wrong");
		} else {
			return userList.get(0).getBean();
		}

	}
}